package com.example.demo.common.config;

import com.example.demo.common.annotation.SkipToken;
import com.example.demo.entity.pojo.user.UserPoJo;
import com.example.demo.module.user.service.UserService;
import com.example.demo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截器.
 *
 * @author Mei Ruoxiao
 * @since 2020/8/20
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("preHandle:拦截 [request:{}, response:{}, handler:{}]", request, response, handler);
        log.info(request.getRequestURI());
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");

//        log.info("preHandle:TOKEN 为[token:{}]", token);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有SkipToken注释，有则跳过认证
        if (method.isAnnotationPresent(SkipToken.class)) {
            log.info("跳过认证");
            SkipToken loginToken = method.getAnnotation(SkipToken.class);
            if (loginToken.required()) {
                return true;
            }
        } else if (token == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return true;
        } else {
            // 获取 token 中的 userId
            long userId = JwtUtil.getUserId(token);
            UserPoJo user = userService.getById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在，请重新登录");
            }
            Boolean verify = JwtUtil.verify(token);
            if (!verify) {
                throw new RuntimeException("非法访问！");
            }
            return true;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
